import { login, getUserInfo, getBaseInfo } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
const state = {
  token: getToken() || '',
  userInfo: {}
}

const mutations = {
  // 设置token
  setToken(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  // 清除token
  removeToken(state) {
    state.token = ''
    removeToken()
  },

  // 设置用户信息
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  },
  // 清除用户信息
  removeUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  // 登录功能
  async login({ commit }, data) {
    const res = await login(data)
    commit('setToken', res.data)
    return res
  },
  // 获取用户信息
  async getUserInfo({ commit }) {
    const res1 = await getUserInfo()
    const res2 = await getBaseInfo(res1.data.userId)
    const res = { ...res1.data, ...res2.data }
    commit('setUserInfo', res)
  },
  // 退出功能
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
  }
}

const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  getters,
  actions
}
